package com.hzit.servlet;



import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.common.utils.R;
import com.hzit.entity.Student;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private List<Student> studentList = new ArrayList<>();
	@Override
	public void init() throws ServletException {
		Student stud1 = new Student(1001,"张三","男",20,"上海",1);
		Student stud2 = new Student(1002,"李四","男",19,"杭州",2);
		Student stud3 = new Student(1003,"王五","女",21,"深圳",3);
		Student stud4 = new Student(1004,"小明","女",20,"珠海",4);
		studentList.add(stud1);
		studentList.add(stud2);
		studentList.add(stud3);
		studentList.add(stud4);

	}

	// @Override
	// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// 	System.out.println("doGet...");
	// }
	//
	// @Override
	// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// 	this.doGet(req,resp);
	// }

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 指定响应类型为json
		resp.setContentType("application/json;charset=utf8");
		String cmd = req.getParameter("cmd");
		if (StrUtil.isNotBlank(cmd)) {
			if("list".equals(cmd)){
				list(req,resp);
			}
		}
		// 将集合转换为字符串
		// String s = JSON.toJSONString(studentList);
		// System.out.println("studentList = " + studentList);
	}
	// 1. 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 指定响应类型为json
		R r = R.ok().data("list", studentList);
		String str = JSON.toJSONString(r);
		// 将字符串输出
		resp.getWriter().print(str);
		resp.getWriter().flush();
	}

	@Override
	public void destroy() {
		System.out.println("servlet销毁");
	}
}
